/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.minidota.arrays;

import com.minidota.game.Room;
import com.minidota.model.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 *
 * @author custom
 */
public class UsersList extends CopyOnWriteArrayList<User> {

    private final Room room;

    public UsersList(Room room) {
        this.room = room;
    }

    public User getById(int id) {
        for (User user : this) {
            if (id == user.getId()) {
                return user;
            }
        }
        return null;
    }

    /**
     * Добавление нового элемента в коллекцию
     *
     * @param e
     * @return
     */
    @Override
    public boolean add(User e) {
        boolean res = false;
        synchronized (this) {
            if (getById(e.getId()) != null) {
                return res;
            }
            e.setGameId(getFreeUserGameId());
            res = super.add(e);
        }
        if (res) {
            //RoomImpl.getInstance().insertPlayerIntoRoom(room, e);
        }
        return res;
    }

    public int getFreeUserGameId() {
        return room.getFreeGameId();
    }

    /**
     * Удаление элемента из коллекции
     *
     * @param o
     * @return
     */
    @Override
    public boolean remove(Object o) {
        boolean res = false;
        if (o instanceof User) {
            User user = (User) o;
            synchronized (this) {
                res = super.remove(user);
            }
            if (res) {

            }
        }
        return res;
    }
}
